/*
 * @Descripttion: 
 * @Author: zhanyi
 * @Date: 2021-10-20 16:05:00
 * @FilePath: \wczd-mobile\src\store\modules\user.js
 */
import { login, logout, getInfo, loginByPhone } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { sureChangeUser } from '@/api/user'

const user = {
  state: {
    token: getToken(),
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
  },

  actions: {
    // 登录
    Login ({ dispatch, commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          if (res.code === 200 && res?.token) {
            setToken(res.token)
            commit('SET_TOKEN', res.token)
						dispatch('GetInfo').then(()=>{
							resolve()
						})
          } else {
            reject(res.msg)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
		// 手机验证码登录
		loginByPhone ({ dispatch,commit }, userInfo) {
		  return new Promise((resolve, reject) => {
		    loginByPhone(userInfo).then(res => {
		      if (res.code === 200 && res?.token) {
		        setToken(res.token)
		        commit('SET_TOKEN', res.token)
						dispatch('GetInfo').then(()=>{
							resolve()
						})
		      } else {
		        reject(res.msg)
		      }
		    }).catch(error => {
		      reject(error)
		    })
		  })
		},
    // 登录
    sureChangeUser({ dispatch, commit }, params) {
      return new Promise((resolve, reject) => {
        sureChangeUser(params).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
					dispatch('GetInfo').then(()=>{
						resolve()
					})
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ dispatch, commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          if (res.permissions) { // 验证返回的roles是否是一个非空数组
            commit('SET_PERMISSIONS', res.permissions)
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user
